package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> list() {
        return addressBookMapper.list(BaseContext.getCurrentId());
    }

    @Override
    public AddressBook getDefault() {
        return addressBookMapper.getDefaultOrNot(BaseContext.getCurrentId(), StatusConstant.ENABLE);
    }

    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    @Override
    public void delete(Long id) {
        addressBookMapper.deleteById(id);
    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        if (addressBook.getIsDefault() == null) {
            addressBook.setIsDefault(StatusConstant.DISABLE);
        }
        addressBookMapper.insert(addressBook);
    }

    @Override
    public void updateDefault(Integer id) {
        //如果有默认地址，则把当前的默认地址设置为非默认
        AddressBook oldDefault = getDefault();
        if (oldDefault != null) {
            addressBookMapper.updateIsDefault(Integer.valueOf(oldDefault.getId().toString()), StatusConstant.DISABLE);
        }
        addressBookMapper.updateIsDefault(id, StatusConstant.ENABLE);
    }
}
